package meiyunting.shiwuzhaoling.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 负载均衡可视化控制器
 * 提供一个页面，让用户可以看到负载均衡效果
 */
@Slf4j
@Controller
@RequestMapping("/loadbalancer")
public class LoadBalancerViewController {

    @Autowired
    private RestTemplate restTemplate;
    
    @Value("${server.port}")
    private String serverPort;
    
    /**
     * 显示负载均衡测试页面
     */
    @GetMapping("")
    public String showLoadBalancerPage(Model model) {
        model.addAttribute("currentPort", serverPort);
        return "loadbalancer";
    }
    
    /**
     * 调用服务实例并返回结果
     */
    @GetMapping("/call")
    @ResponseBody
    public Map<String, Object> callService() {
        System.out.println("\n\n====================================================");
        System.out.println("【控制台输出-重要信息】从端口 " + serverPort + " 发起调用实例信息请求");
        
        // 使用服务名称而不是具体URL，这会触发负载均衡
        Map<String, Object> result = restTemplate.getForObject("http://lost-found-service/api/instance/info", Map.class);
        
        System.out.println("【控制台输出-重要信息】请求被路由到端口: " + result.get("port"));
        System.out.println("====================================================\n\n");
        
        // 添加当前端口信息
        Map<String, Object> response = new HashMap<>(result);
        response.put("sourcePort", serverPort);
        
        return response;
    }
} 